package cn.xtits.design.controller;

import cn.xtits.design.entity.LabelImage;
import cn.xtits.design.entity.LabelImageExample;
import cn.xtits.design.entity.Pagination;
import cn.xtits.design.enums.ErrorCodeEnums;
import cn.xtits.design.service.LabelImageService;
import cn.xtits.design.util.FileUtil;
import cn.xtits.design.util.GenerateGUID;
import cn.xtits.design.util.MD5Util;
import cn.xtits.design.util.StringUtil;
import cn.xtits.xtf.common.utils.JsonUtil;
import cn.xtits.xtf.common.web.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @fileName: LabelImageController.java
 * @author: Dan
 * @createDate: 2019-10-08 16:23:26
 * @description: 图片
 */
@RestController
@RequestMapping("/labelImage")
public class LabelImageController extends BaseController {

    @Value("${pldesign.upload.printerRootUrl}")
    private String printerRootUrl;

    @Value("${pldesign.upload.printerFileUrl}")
    private String printerFileUrl;

    @Value("${pldesign.upload.printerStaticUrl}")
    private String printerStaticUrl;

    @Value("${pldesign.upload.labelImageFileDir}")
    private String labelImageFileDir;

    @Autowired
    private LabelImageService service;

    //@RequiresPermissions("labelimage:insert")
    @RequestMapping(value = "insertLabelImage")
    public AjaxResult insertLabelImage(
            @RequestParam(value = "data", required = false) String data) {
        LabelImage record = JsonUtil.fromJson(data, LabelImage.class);
        //Date dt = getDateNow();
        record.setCreateDate(null);
        record.setMakeBillMan(getUserName());
        record.setModifier(getUserName());
        record.setModifyDate(null);
        record.setDeleteFlag(false);
        service.insert(record);
        return new AjaxResult(record);
    }

    //@RequiresPermissions("labelimage:delete")
    @RequestMapping(value = "deleteLabelImage")
    public AjaxResult deleteLabelImage(
            @RequestParam(value = "id", required = false) int id) {
        LabelImage record = new LabelImage();
        record.setId(id);
        record.setDeleteFlag(true);
        record.setModifier(getUserName());
        record.setModifyDate(null);
        int row = service.updateByPrimaryKeySelective(record);
        return new AjaxResult(row);
    }

    //@RequiresPermissions("labelimage:update")
    @RequestMapping(value = "updateLabelImage")
    public AjaxResult updateLabelImage(
            @RequestParam(value = "data", required = false) String data) {
        LabelImage record = JsonUtil.fromJson(data, LabelImage.class);
        record.setCreateDate(null);
        record.setMakeBillMan(null);
        record.setModifyDate(null);
        record.setModifier(getUserName());
        record.setDeleteFlag(false);
        service.updateByPrimaryKeySelective(record);
        return new AjaxResult(record);
    }

    @RequestMapping(value = "listLabelImage")
    public AjaxResult listLabelImage(
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "url", required = false) String url,
            @RequestParam(value = "md5", required = false) String md5,
            @RequestParam(value = "appId", required = false) String appId,
            @RequestParam(value = "systemFlag", required = false) Boolean systemFlag,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        LabelImageExample example = new LabelImageExample();
        example.setPageIndex(pageIndex);
        example.setPageSize(pageSize);
        if (StringUtils.isNotBlank(orderBy)) {
            example.setOrderByClause(orderBy);
        }
        LabelImageExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteFlagEqualTo(false);

        if (StringUtils.isNotBlank(code)) {
            criteria.andCodeLike(code);
        }
        if (StringUtils.isNotBlank(name)) {
            criteria.andNameLike(name);
        }
        if (StringUtils.isNotBlank(url)) {
            criteria.andUrlLike(url);
        }
        if (StringUtils.isNotBlank(md5)) {
            criteria.andMd5Like(md5);
        }
        if (StringUtils.isNotBlank(appId)) {
            String[] split = appId.split(",");
            if (split.length > 1) {
                List<Integer> appIdList = new ArrayList<>();
                for (String s : split) {
                    appIdList.add(Integer.parseInt(s));
                }
                criteria.andAppIdIn(appIdList);
            } else {
                criteria.andAppIdEqualTo(Integer.parseInt(split[0]));
            }
        }

        if (systemFlag != null) {
            criteria.andSystemFlagEqualTo(systemFlag);
        }
        if (StringUtils.isNotBlank(startDate)) {
            criteria.andCreateDateGreaterThanOrEqualTo(DateTime.parse(startDate, format).toDate());
        }
        if (StringUtils.isNotBlank(endDate)) {

            criteria.andCreateDateLessThanOrEqualTo(DateTime.parse(endDate, format).toDate());
        }

        List<LabelImage> list = service.listByExample(example);
        Pagination<LabelImage> pList = new Pagination<>(example, list, example.getCount());
        return new AjaxResult(pList);
    }

    @RequestMapping(value = "getLabelImage")
    public AjaxResult getLabelImage(
            @RequestParam(value = "id", required = false) Integer id) {
        LabelImage res = service.getByPrimaryKey(id);
        return new AjaxResult(res);
    }

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "insertLabelImageUpload")
    public AjaxResult insertLabelImageUpload(
            @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
            @RequestParam(value = "data", required = false) String data) {
        LabelImage record = JsonUtil.fromJson(data, LabelImage.class);
        if (exist(record) > 0) {
            return new AjaxResult(-1, "存在相同的名称!");
        }

        if (imageFile == null) {
            return new AjaxResult(ErrorCodeEnums.SERVER_ERROR.value, "请上传文件", null);
        }

        boolean picFlag = false;
        boolean uploadFlag = false;
        if (imageFile != null) {
            if (record.getId() > 0) {
                LabelImage res = service.getByPrimaryKey(record.getId());
                if (StringUtils.isNotBlank(res.getUrl())) {
                    uploadFlag = !res.getUrl().contains(StringUtil.convertStringToUTF8(record.getUrl()));
                } else {
                    uploadFlag = true;
                }
            } else {
                uploadFlag = true;
            }
        } else {
            if (!StringUtils.isNotBlank(record.getUrl())) {
                return new AjaxResult(-1, "请先上传文件!");
            }
        }

        if (uploadFlag) {
            //存放目录
            String path = FileUtil.createMkdirMulti(printerRootUrl, true, printerFileUrl, labelImageFileDir);

            //新文件名称
            String newFileName = FileUtil.fileExistsRenameFlag(path, imageFile.getOriginalFilename(), ".");

            //文件全路径
            String fileUrl = FileUtil.getSpliceSuffix(path, newFileName);

            //上传文件
            picFlag = fileUpload(imageFile, fileUrl);
            String fileMD5 = MD5Util.getMd5ByPath(fileUrl);
            record.setMd5(fileMD5);
            record.setUrl(printerStaticUrl + "/" + labelImageFileDir + "/" + newFileName);
        }

        if (record.getId() > 0) {
            record.setAppId(getAppId());
            record.setCreateDate(null);
            record.setMakeBillMan(null);
            record.setModifyDate(null);
            record.setModifier(getUserName());
            record.setDeleteFlag(false);
            service.updateByPrimaryKeySelective(record);
        } else {
            record.setAppId(getAppId());
            record.setCode(GenerateGUID.generateGUID());
            record.setCreateDate(null);
            record.setMakeBillMan(getUserName());
            record.setModifier(getUserName());
            record.setModifyDate(null);
            record.setDeleteFlag(false);
            service.insert(record);
        }
        return new AjaxResult(ErrorCodeEnums.NO_ERROR.value, "添加成功!", record);
    }

    private int exist(LabelImage entity) {
        LabelImageExample example = new LabelImageExample();
        example.setPageSize(1);
        LabelImageExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteFlagEqualTo(false);
        if (entity.getId() != null && entity.getId() > 0) {
            criteria.andIdNotEqualTo(entity.getId());
        }
        criteria.andUrlEqualTo(entity.getUrl());
        return service.listByExample(example).size();
    }

    /**
     * 上传文件
     *
     * @param file 文件
     */
    private boolean fileUpload(MultipartFile file, String path) {
        if (file != null && !file.isEmpty()) {
            File localFile = new File(path);
            try {
                file.transferTo(localFile);
                return true;
            } catch (IOException e) {
                System.out.println("上传文件失败!" + e.getMessage());
            }
        }
        return false;
    }

}